package com.zsh.web;

import com.zsh.pojo.Book;
import com.zsh.pojo.Page;
import com.zsh.service.BookService;
import com.zsh.service.impl.BookServiceImpl;
import com.zsh.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ClientBookServlet extends BaseServlet {
    private BookService bookService = new BookServiceImpl();

    /**
     * 处理分页
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("经过了前天的clientBookServlet");
        //1.获得请求参数，pageNo和pageSize
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        //2.调用bookService.page(pageNo,pageSize)
        Page<Book> page = bookService.page(pageNo,pageSize);



        page.setUrl("client/bookServlet?action=page");
        //3.保存PAge对象到requset
        request.setAttribute("page",page);
        //4.请求转发
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);


    }

    /**
     * 价格搜素功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void pageByPrice(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("经过了前天的clientBookServlet");
        //1.获得请求参数，pageNo和pageSize
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        int min = WebUtils.parseInt(request.getParameter("min"),0);
        int max = WebUtils.parseInt(request.getParameter("max"),Integer.MAX_VALUE);
        //2.调用bookService.page(pageNo,pageSize)
        Page<Book> page = bookService.pageByPrice(pageNo,pageSize,min,max);
        StringBuilder sb = new StringBuilder("client/bookServlet?action=pageByPrice");
        if (request.getParameter("min") != null){
            sb.append("&min=").append(request.getParameter("min"));
        }

        if (request.getParameter("max") != null){
            sb.append("&max=").append(request.getParameter("max"));
        }

        page.setUrl(sb.toString());
        //3.保存PAge对象到requset
        request.setAttribute("page",page);
        //4.请求转发
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);


    }
}
